package net.ifilm.db;

import net.ifilm.common.SpiderException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-7-16
 * Time: 上午10:16
 * To change this template use File | Settings | File Templates.
 */
public class DBTemplate {

    public Object query(String sql, Object[] params, ResultCallback resultCallback) throws SpiderException {
        Object object = null;

        try {
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            try {
                conn = DBConnectionUtil.getInstance().getConnection();
                pstmt = conn.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i+1, params[i]);
                }
                rs = pstmt.executeQuery();
                object = resultCallback.callback(rs);

                return object;
            } finally {
                DBConnectionUtil.getInstance().freeResource(conn, pstmt, rs);
            }
        } catch (SQLException e) {
            throw new SpiderException(e.toString());
        }
    }

    public Object update(String sql, Object[] params) throws SpiderException {
        Object object = null;

        try {
            Connection conn = null;
            PreparedStatement pstmt = null;
            try {
                conn = DBConnectionUtil.getInstance().getConnection();
                pstmt = conn.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i+1, params[i]);
                }
                object = pstmt.executeUpdate();
                return object;
            } finally {
                DBConnectionUtil.getInstance().freeResource(conn, pstmt, null);
            }
        } catch (SQLException e) {
            throw new SpiderException(e.toString());
        }
    }

}
